#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h> /* superset of previous */
#include <arpa/inet.h>  /* for sockaddr_in and inet_addr() */

#define N_ROUTINE 7
#define STR_LEN 5

int main()
{
    int                 sockFd              ;
    int                 i                   ;
    size_t              bytesSnt        = 0 ;
    size_t              totalBytesSnt   = 0 ;
    size_t              bytesRcv        = 0 ;
    size_t              totalBytesRcv   = 0 ;
    struct sockaddr_in  addr                ;
    char                recvBuf[200]        ;
    char                sendBuf[] = "World" ;

    sockFd = socket(AF_INET,        /*  Specifies the communications domain in which a socket is to be created  */
                   SOCK_STREAM ,    /*  Specifies the type of socket to be created.   */
                   IPPROTO_TCP);    /*  Specifies a particular protocol to be used with the socket. Specifying a protocol of 0 causes socket() to use an unspecified default proto‐
                                        col appropriate for the requested socket type.    */
    if(sockFd == -1)
    {
        perror("socket");
        return 1;
    }

    /* Construct the server sockaddr_in structure */
    memset(&addr, 0, sizeof(addr));                 /* Clear struct */
    addr.sin_family = AF_INET;                      /* Internet/IP  */
    addr.sin_addr.s_addr =inet_addr("127.0.0.1");   /* IP address   */
    addr.sin_port = 7;                              /* server port */

    if (connect(sockFd,                 /*  socket file descriptor                                  */
        (struct sockaddr *) &addr,      /*  assigns the address specified to the socket             */
        sizeof(addr)) < 0)              /*  specifies the size, in bytes, of the address structure  */
    {
        perror("connect");
        close(sockFd);
        return 1;
    }

    for(i = 0; i < N_ROUTINE; ++i)
    {
	totalBytesRcv = 0;
        while(totalBytesRcv < STR_LEN )
        {
            if((bytesRcv = recv(sockFd, recvBuf + totalBytesRcv, STR_LEN - totalBytesRcv, 0)) <= 0)
            {
                perror("recv");
                return 1;
            }
            totalBytesRcv += bytesRcv;
        }
        if(totalBytesRcv == STR_LEN)
        {
            
        }
        *(recvBuf + STR_LEN) = '\0';
        printf("%s\n", recvBuf);

        sleep(2);
	
	totalBytesSnt = 0;
        while(totalBytesSnt < STR_LEN)
        {
            if((bytesSnt = send(sockFd, sendBuf + totalBytesSnt, STR_LEN -  totalBytesSnt, 0)) == -1)
            {
                perror("send");
                return 1;
            }
            totalBytesSnt += bytesSnt;
        }
        if(totalBytesSnt == STR_LEN)
        {
            totalBytesSnt = 0;
        }
    }

    close(sockFd);

    return 0;

}

